package com.onesports.intelligent.k12.polarlight.security.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.onesports.intelligent.k12.polarlight.cache.RedisTokenProvider;
import com.onesports.intelligent.k12.polarlight.security.jwt.JwtTokenProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author aj
 */
public class WxAuthenticationFilterConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final WxMaService wxMaService;
    private final WxAuthenticationProvider wxAuthenticationProvider;
    private final JwtTokenProvider jwtTokenProvider;
    private final RedisTokenProvider redisTokenProvider;


    public WxAuthenticationFilterConfigurer(WxAuthenticationProvider wxAuthenticationProvider,
                                            WxMaService wxMaService,
                                            JwtTokenProvider jwtTokenProvider,
                                            RedisTokenProvider redisTokenProvider) {
        this.wxMaService = wxMaService;
        this.wxAuthenticationProvider = wxAuthenticationProvider;
        this.jwtTokenProvider = jwtTokenProvider;
        this.redisTokenProvider = redisTokenProvider;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        WxAuthenticationFilter authenticationFilter = new WxAuthenticationFilter(wxMaService);
        authenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        authenticationFilter.setAuthenticationSuccessHandler(new WxLoginSuccessHandler(jwtTokenProvider, redisTokenProvider));
        authenticationFilter.setAuthenticationFailureHandler(new WxLoginFailHandler());
        http.authenticationProvider(wxAuthenticationProvider)
                .addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
